package com.example.fragmentdemo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;

import android.os.Bundle;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        intiPage();
    }
    private void intiPage(){
        ViewPager viewPager=findViewById(R.id.view_page);
        List<Fragment> list=new ArrayList<>();
        list.add(new StaticFragment());
        list.add(new DynamicFragment());
        list.add(new ThridFragment());
        ViewPagerAdapter adapter=new ViewPagerAdapter(getSupportFragmentManager(),
                FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        adapter.setFragments(list);
        viewPager.setAdapter(adapter);
        //将数据缓存在ViewModel
        MyViewModel.getInstance().setData("ViewModel");
    }
    private void intiView() {

        //获取FragmentManager
        FragmentManager fm = getSupportFragmentManager();
        //获取FragmentTransaction
        FragmentTransaction ft = fm.beginTransaction();
        //添加Fragment
        DynamicFragment fragmnet = new DynamicFragment();
        ft.add(R.id.fragme_two, fragmnet);

        ThridFragment thrid=new ThridFragment();
        Bundle bundle=new Bundle();
        bundle.putString("activity_data","shiju");
        thrid.setArguments(bundle);



        ft.add(R.id.fragme_two,thrid);
        //提交 操作完成后必须提交
        //同一个FragmentTransaction只可以提交一次 不可重复操作
        ft.commit();
        //为了避免FragmentTransaction重复使用
        getSupportFragmentManager().beginTransaction().add(R.id.fragme_two, new DynamicFragment()).commit();
    }
    public String sendData(){
        return "hello";
    }

        class  ViewPagerAdapter extends FragmentPagerAdapter{
            private  List<Fragment> fragments;

            public void setFragments(List<Fragment> fragments) {
                this.fragments = fragments;
            }

            public ViewPagerAdapter(@NonNull FragmentManager fm, int behavior) {
                super(fm, behavior);
            }

            @NonNull
            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public int getCount() {
                return null!=fragments?fragments.size():0;
            }
        }



}